package com.bs.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2015/11/23.
 */
public class iPlat4CHttpClient {
//    private static String BASE_URL = "http://190.2.246.4:8000/Service/rest/CallCpp";
    public static String post(String baseUrl, String ParamJsonString) {
        String responseString=null;
        HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
        try {
            HttpPost request = new HttpPost(baseUrl);
            ParamJsonString = new String(ParamJsonString.getBytes("UTF-8"), "iso-8859-1");
            StringEntity params =new StringEntity(ParamJsonString);
            request.addHeader("Content-type", "application/json");
            request.setEntity(params);
            HttpResponse response = httpClient.execute(request);
            //handle response here...
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatusLine().getStatusCode());
            }
            System.out.println(response.getEntity().getContent());

            BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

            String output;
            StringBuffer totalOutput = new StringBuffer();
            //System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                //System.out.println(output);
                totalOutput.append(output);
            }
            String resp = totalOutput.toString().replaceAll("[\uFEFF-\uFFFF]", "");
            return resp;

        }catch (Exception ex) {
            //handle exception here
            ex.printStackTrace();

        } finally {
            //Deprecated
            responseString=null;
            httpClient.getConnectionManager().shutdown();
        }
        return responseString;
    }

}
